<?php
/**
* Profiling tools to measure runtime performance.
*<p>Create a new <i>Profile</i> instance each time you want a different timer. Then call <i>Stop()</i> method
*to stop the timer.</p>
*<p>Example:<code>
* $timer = new CoreProfile("my_timer");
* .. do some stuff...
* $timer->Stop();
*</code></p>
*<p>This uses the PHP internal micro-seconds timer, so this is not very accurate. Use as a thumb-size measurement.
*</p><p>
*To get output use either:
*<ul><li><i>GetTime()</i>: Get time in milliseconds</li>
*<li><i>PrintHuman()</i>: write a nice string</li>
*<li><i>Dump()</i>: (static member) dump all timers at once</li></ul></p>
*@author Willy Gardiol <willy@gardiol.org>
*@version 1.0
*@package Core
*@subpackage Profile
*/
class CoreProfile
{
	static private $timers = array();
	static private function GetUSecs()
	{
		return microtime(true);
	}
	/**
	* Print all the existing timers in HTML format
	*@return mixed HtmlTag structured HTMl output
	*/
	static public function Dump()
	{
		global $overall_profile;
		$overall_profile->Stop();

		$profiles = array();
		foreach ( CoreProfile::$timers as $p )
			$profiles[] = array( "text" => $p->text, "time" => $p->GetTime() );
		$output = new HtmlTemplate("core:profile", array("profiles" => $profiles));
		$output->DrawHtml();
	}

	private $text = "";
	private $start_time = false;
	private $end_time = false;
	/**
	* Construct and start the timer.
	*@param string $text is the identifier of this timer (for reference AND human readable output so be meaningful and short please)
	*/
	public function __construct( $text )
	{
		$this->text = $text;
		$this->start_time = CoreProfile::GetUSecs();
		CoreProfile::$timers[] = $this;
	}
	/**
	* Stop the timer
	*/
	public function Stop()
	{
		$this->end_time = CoreProfile::GetUSecs();
	}
	/**
	* Print the timer value in human readable format: which means in seconds.
	* Eample: <i>"Profiling for startup_engine: 0.345 seconds"</i>
	*@return string
	*/
	public function PrintHuman()
	{
		return I18N("Profiling for")." ".$this->text.": ".$this->GetTime()." ".I18N("millisecs");
	}
	/**
	* return time in milliseconds
	*@return integer
	*/
	public function GetTime()
	{
		return round($this->end_time - $this->start_time,6)*1000;
	}
}
$overall_profile = new CoreProfile("Overall page time");

?>